import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/material.dart';
import '../../theme/theme_color.dart';
import 'blind_detail.dart';

/// 诚信约会
class BlindTrustUi extends StatelessWidget {
  const BlindTrustUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _BlindTrustWidget();
  }
}

class _BlindTrustWidget extends StatefulWidget {
  const _BlindTrustWidget({Key? key}) : super(key: key);

  @override
  State<_BlindTrustWidget> createState() => _BlindTrustWidgetState();
}

class _BlindTrustWidgetState extends State<_BlindTrustWidget>
    with TickerProviderStateMixin {
  final _titles = ["诚信约会", "我的邀约", "我的赴约"];
  final _lists = <List>[];
  final _pageNoArr = <int>[];
  late TabController _tabController;
  late PageController _pageController;
  late ScrollController _scrollController;

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      title: "诚信约会",
      rightActions: [
        GestureDetector(
            onTap: () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (builder) => const BlindDetailUi(
                        datingId: null,
                      )));
            },
            child: Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: ShapeDecoration(
                  color: ThemeColor.mainColor,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16))),
              child: const Text(
                "去发布",
                style: TextStyle(color: Colors.white, fontSize: 12),
              ),
            ))
      ],
      childWidget: Column(
        children: [_buildTabBar(), Expanded(child: _buildPageView())],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _titles.length, vsync: this);
    _pageController = PageController();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      int index = _tabController.index;
      _pageNoArr[index]++;
      _getData();
    });
    for (var s in _titles) {
      _lists.add([]);
      _pageNoArr.add(1);
    }
    _getData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  void _onTabChanged(int index) {
    _pageController.animateToPage(index,
        duration: const Duration(milliseconds: 300), curve: Curves.ease);
  }

  void _onPageChanged(int index) {
    _tabController.animateTo(index,
        duration: const Duration(milliseconds: 300));
  }

  Future<void> _onRefresh() async {
    _pageNoArr[_tabController.index] = 1;
    _getData();
  }

  Widget _buildTabBar() {
    return TabBar(
      controller: _tabController,
      tabs: _titles.map((e) => Tab(text: e)).toList(),
      labelColor: ThemeColor.textColor,
      labelStyle: TextStyle(
          color: ThemeColor.textColor,
          fontWeight: FontWeight.bold,
          fontSize: 16),
      unselectedLabelColor: ThemeColor.textColorSecond,
      unselectedLabelStyle:
          TextStyle(color: ThemeColor.textColorSecond, fontSize: 14),
      isScrollable: false,
      indicatorColor: ThemeColor.mainColor,
      indicatorSize: TabBarIndicatorSize.label,
      indicatorPadding: const EdgeInsets.symmetric(horizontal: 10),
      onTap: _onTabChanged,
    );
  }

  Widget _buildPageView() {
    return PageView.builder(
      controller: _pageController,
      physics: const BouncingScrollPhysics(),
      itemCount: _titles.length,
      onPageChanged: _onPageChanged,
      itemBuilder: (context, index) {
        return _buildListView(index);
      },
    );
  }

  Widget _buildListView(int position) {
    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: ListView.builder(
          itemCount: _lists[position].length,
          itemBuilder: (context, index) {
            return _buildListItem(_lists[position][index]);
          }),
    );
  }

  Widget _buildListItem(item) {
    double age = (DateTime.now().millisecondsSinceEpoch -
            DateTime.parse(item['birthYear']).millisecondsSinceEpoch) /
        1000 /
        60 /
        60 /
        24 /
        365;
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      height: 70,
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(width: 1, color: ThemeColor.dividerColor))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(20),
            child: Image.network(
              item['avatarImg'],
              width: 40,
              height: 40,
              fit: BoxFit.fill,
            ),
          ),
          const SizedBox(
            width: 8,
          ),
          Expanded(
            child: SizedBox(
              height: 40,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        "${item['nickName']}    ",
                        style: TextStyle(
                            color: ThemeColor.textColor, fontSize: 15),
                      ),
                      AppWidget.genderAndAge(item['realSex'], age.round())
                    ],
                  ),
                  Text(
                    "${item['type']}  ${item['startTimeFormat']} ${item['location']}",
                    style: TextStyle(
                        fontSize: 12, color: ThemeColor.textColorSecond),
                  )
                ],
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              String id = item['id']?.toString() ?? "";
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (builder) =>
                      BlindDetailUi(datingId: id, type: _tabController.index)));
            },
            child: Container(
              width: 56,
              height: 24,
              decoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(12)),
                border: Border.all(width: 1, color: ThemeColor.mainColor),
              ),
              alignment: Alignment.center,
              child: Text(
                "查看",
                style: TextStyle(color: ThemeColor.mainColor, fontSize: 12),
              ),
            ),
          )
        ],
      ),
    );
  }

  _getData() async {
    final type = _tabController.index;
    final res =
        await Api.getInstance().getFaithDatingList(type, _pageNoArr[type], 20);
    if (res == null) {
      ThemeSnackBar.show(context, "暂无数据");
      return;
    }
    if (res['code'] != 0) {
      ThemeSnackBar.show(context, res['msg']);
      return;
    }
    if (res['data'] == null || res['data']['list'] == null) {
      ThemeSnackBar.show(context, "暂无数据");
      return;
    }
    List resList = res['data']['list'];
    if (resList.isEmpty) {
      ThemeSnackBar.show(context, '暂无数据');
      return;
    }
    if (_pageNoArr[type] <= 1) {
      _lists[type].clear();
    }
    setState(() {
      _lists[type].addAll(resList);
    });
  }
}
